package com.example.forum.services.impl;


import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleReplyMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.ArticleReply;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import com.example.forum.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:帖子回复相关的业务实现
 * User: liuli
 * Date: 2024-08-14
 * Time: 18:51
 */

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    // 注⼊DAO层
    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private IArticleService articleService;


    @Override
    public void create(ArticleReply articleReply) {
        // ⾮空校验
        if (articleReply == null || articleReply.getArticleId() == null
              || articleReply.getArticleId() == null
              || articleReply.getPostUserId() == null
              || StringUtil.isEmpty(articleReply.getContent())) {

            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 填充默认数据
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setState((byte) 0); // 状态
        articleReply.setDeleteState((byte) 0); // 是否状态
        articleReply.setLikeCount(0); // 点赞数量
        // 时间
        Date date = new Date();
        articleReply.setCreateTime(date); // 创建时间
        articleReply.setUpdateTime(date); // 更新时间
        // 写⼊回复数据
        int row = articleReplyMapper.insertSelective(articleReply);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        // 更新帖⼦回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("回复成功，article id = "+ articleReply.getArticleId() + "，user id = " + articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        // ⾮空校验
        if (articleId == null || articleId == 0) {
            // 记录日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调⽤DAO层查询结果
        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);
        // 返回结果
        return result;
    }
}
